//
//  XPCustomHeader.swift
//  PPKit
//
//  Created by xiaopin on 2019/8/21.
//  Copyright © 2019 PPKit. All rights reserved.
//  https://gitee.com/xiaopindev/PPKit
//  https://github.com/xiaopindev
//  https://xiaopin.cnblogs.com

import MJRefresh
import Kingfisher

class XPCustomHeader: MJRefreshHeader {
    
    lazy var animateView:UIImageView = {
        let loadingView = UIImageView.aspectFitImageView()
        var images = [UIImage]()
        for i in 1..<9 {
            images.append(UIImage(named: "animation_loading_\(i)_small")!)
        }
        if images.count > 0 {
            loadingView.animationImages = images
            loadingView.animationDuration = 5
            loadingView.startAnimating()
        }
        return loadingView
    }()
    lazy var label:UILabel = {
        let customLabel = UILabel()
        customLabel.textColor = pp_color(.C222222)
        customLabel.font = UIFont.systemFont(ofSize: 12)
        customLabel.textAlignment = .center
        return customLabel
    }()

    /// 在这里做一些初始化配置（比如添加子控件）
    override func prepare() {
        super.prepare()
        
        mj_h = 60
        addSubview(label)
        addSubview(animateView)
    }
    
    ///在这里设置子控件的位置和尺寸
    override func placeSubviews() {
        super.placeSubviews()
        animateView.frame = CGRect(x: (mj_w - 40)/2 , y: 0, width: 40, height: 40)
        label.frame = CGRect(x: 0, y: 40, width: mj_w, height: 20)
    }
    
    /// 监听scrollView的contentOffset改变
    override func scrollViewContentOffsetDidChange(_ change: [AnyHashable : Any]!) {
        super.scrollViewContentOffsetDidChange(change)
    }
    
    /// 监听scrollView的contentSize改变
    override func scrollViewContentSizeDidChange(_ change: [AnyHashable : Any]!) {
        super.scrollViewContentSizeDidChange(change)
    }
    
    /// 监听scrollView的拖拽状态改变
    override func scrollViewPanStateDidChange(_ change: [AnyHashable : Any]!) {
        super.scrollViewPanStateDidChange(change)
    }
    
    override var state: MJRefreshState {
        willSet{
            let oldState = self.state
            if newValue == oldState {return}
            
            switch newValue {
            case .idle:
                if animateView.isAnimating { animateView.stopAnimating() }
                self.label.text = "MT_Refresh_Idle".localized
            case .pulling:
                animateView.startAnimating()
                self.label.text = "MT_Refresh_Pulling".localized
            case .refreshing:
                self.label.text = "MT_Refresh_Refreshing".localized
            default:
                break
            }
        }
    }
}
